package com.edfeff.bio.http;


import java.util.ArrayList;
import java.util.List;


/**
 * <pre>
 *          Request       = Request-Line              ; Section 5.1
 *                         *(( general-header        ; Section 4.5
 *                          | request-header         ; Section 5.3
 *                          | entity-header ) CRLF)  ; Section 7.1
 *                         CRLF
 *                         [ message-body ]          ; Section 4.3
 * </pre>
 */
public class Request {
    /**
     * 请求方法字符串 GET POST etc.
     */
    private String method;
    /**
     * 请求URI
     */
    private String uri;
    /**
     * 请求协议版本
     */
    private String protocol;

    /**
     * 请求头
     */
    private List<Header> headers = new ArrayList<>();

    //
    private long startTime = 0L;
    private byte[] body;

    public long getStartTime() {
        return startTime;
    }

    public void setStartTime(long startTime) {
        this.startTime = startTime;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public List<Header> getHeaders() {
        return headers;
    }

    public void setHeaders(List<Header> headers) {
        this.headers = headers;
    }

    public String getMethod() {
        return method;
    }

    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }

    @Override
    public String toString() {
        StringBuilder res = new StringBuilder();
        res.append(method).append(" ").append(uri).append(" ").append(protocol).append("\r\n");
        headers.forEach(h -> res.append(h.toString()).append("\r\n"));
        return res.toString();
    }

    void show() {
        System.out.println();
        System.out.print(this);
        System.out.println();
    }

    public String getContentType() {
        Header header = getHeader("content-type");
        if (header != null) {
            return header.getValue();
        }
        return null;
    }

    public long getContentLengthLong() {
        long length = -1;
        try {
            Header header = getHeader("content-length");
            if (header != null) {
                length = Long.parseLong(header.getValue());
            }
        } catch (NumberFormatException e) {
        }
        return length;
    }

    public Header getHeader(String headerName) {
        //todo 哈希优化
        for (Header header : headers) {
            if (headerName.equals(header.getName()))
                return header;

        }
        return null;
    }

    public void setBody(byte[] body) {
        this.body = body;
    }

    public byte[] getBody() {
        return body;
    }
}
